package nio.cp3_channel;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

public class ChannelCopy {

    public static void main(String[] args) throws IOException {
        ReadableByteChannel read = Channels.newChannel(System.in);
        WritableByteChannel write = Channels.newChannel(System.out);
        channelCopy1(read,write);
//        channelCopy2(read,write);
        read.close();
        write.close();

    }
    private static void channelCopy1 (ReadableByteChannel src,
                                      WritableByteChannel dest) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
        while (src.read(buffer) != -1) {
            buffer.flip();
            dest.write(buffer);
            buffer.compact();
            buffer.flip();
            while (buffer.hasRemaining()) {
                dest.write(buffer);
            }
            buffer.clear();


        }
    }
    private static void channelCopy2 (ReadableByteChannel src,
                                      WritableByteChannel dest)
            throws IOException
    {
        ByteBuffer buffer = ByteBuffer.allocateDirect (16 * 1024);

        while (src.read(buffer) != -1) {
            buffer.flip();

            while (buffer.hasRemaining()) {
                dest.write(buffer);
            }

            buffer.clear();

        }
    }
}
